part of AppUtils;

extension Intent on _AppUtils {
  void reLaunchApp({bool goLogin = false, bool deleteUser = false}) {
    IFinal.Others.mainPage.pageController.jumpToPage(0);
    if (deleteUser) deleteUserModel();
    yRun(() {
      goHome(goLogin: goLogin);
    });
  }

  void goHome({bool goLogin = false, bool reCreateWhenPopToPage = true}) {
    yPages.first.yIntent(MainPage(goLogin: goLogin), intentType: YIntentType.Root_Replace, popToPage: true, reCreateWhenPopToPage: reCreateWhenPopToPage);
  }

  void switchScheme(YPage page, String? uri, {bool showErrorToast = true}) {
    void doScheme(YPage page, Map<String, String> params) {
      switch (params["action"]) {
        case "goProductDetail": //跳转商品
          goIntent(page, Enum_IntentType.GoProductDetail, params: {
            "id": params["id"],
          });
          break;
        default:
          if (showErrorToast) yToast("当前版本尚不支持，请更新应用");
          break;
      }
    }

    if (uri == null) return;
    if (uri.isEmpty) {
      if (showErrorToast) yToast("内容为空");
      return;
    }
    if (uri.startsWith("http://") || uri.startsWith("https://"))
      launchUrl(Uri.dataFromString(uri));
    else if ((yIsWeb || uri.startsWith(IFinal.Configs_Local.scheme)) && uri.contains("?")) {
      Map<String, String> params = {};
      uri.split("?").last.split("&").forEach((element) {
        var param = element.split("=");
        params[param[0]] = param[1].toString();
      });
      doScheme(page, params);
    } else if (showErrorToast) yToast("不支持的格式，内容：\n$uri");
  }

  Future<void> goIntent(YPage page, Enum_IntentType type, {Map<String, dynamic>? params}) async {
    void goProductList(YPage page, String content) {
      yRun(() {
        goHome(reCreateWhenPopToPage: false);
        IFinal.Others.mainPage.yIntent(ProductListPage(content));
      }, delay: yPages.where((element) => element is ProductListPage).isEmpty ? 0 : 100);
    }

    switch (type) {
      case Enum_IntentType.GoProductDetail: //商品详情
        var id = params?["id"];
        page.yIntent(ProductDetailPage(id), popToPage: true, reCreateWhenPopToPage: true);
        break;
      // case Enum_IntentType.goProductList_id: //搜索列表_id
      //   var id = params?["id"];
      //   page.yPost<dynamic>(IFinal.jkids.getProductSearchContentById, {
      //     "id": id,
      //   }, (isSuccess, results, code, message) {
      //     if (isSuccess) goProductList(page, results!.first["content"]);
      //   }, cacheEnable: true);
      //   break;
      case Enum_IntentType.GoProductList_content: //搜索列表_内容
        var content = params?["content"];
        goProductList(page, content!);
        break;
      default:
        yToast("当前版本尚不支持，请更新应用");
        break;
    }
  }
}
